package net.siufung.market.base.permit.controller.regulation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import net.siufung.core.exception.BizServiceException;
import net.siufung.core.model.VerifyRepeatDto;
import net.siufung.core.model.enums.MethodEventEnum;
import net.siufung.core.model.regulation.AbstractRegulation;
import net.siufung.market.base.permit.controller.model.dto.MenuSaveDto;
import net.siufung.market.base.permit.controller.model.dto.PermitText;
import net.siufung.market.base.permit.enums.AccessStates;
import net.siufung.market.base.permit.mapper.IMenuMapper;
import net.siufung.market.base.permit.mapper.IPermitMapper;
import net.siufung.market.base.permit.mapper.entity.Permit;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 陈建峰
 * @since 2022/8/8 3:19 下午
 */
@AllArgsConstructor
public class MenuCreateRegulation extends AbstractRegulation<MenuSaveDto> {

    private static final long serialVersionUID = 3843283838095353630L;

    private final IMenuMapper menuMapper;
    private final IPermitMapper permitMapper;


    @Override
    public boolean isSatisfiedBy(MenuSaveDto menuSaveDto) {
        VerifyRepeatDto<Integer> verifyRepeatDto = new VerifyRepeatDto<>();
        verifyRepeatDto.setMethodEventEnum(MethodEventEnum.ADD);
        verifyRepeatDto.setPk(null);
        verifyRepeatDto.setVerifyKeyValue(menuSaveDto.getMenuName());
        if(!menuMapper.checkMenuNameRepeat(verifyRepeatDto)){
            throw new BizServiceException("菜单名称重复！");
        }
        verifyRepeatDto.setVerifyKeyValue(menuSaveDto.getRouter());
        if(!menuMapper.checkMenuRouterRepeat(verifyRepeatDto)){
            throw new BizServiceException("菜单路由重复！");
        }
        if(AccessStates.IS.getValue().equals(menuSaveDto.getAccessState())){
            List<String> permitSignList = menuSaveDto.getPermitTextList().stream()
                    .map(PermitText::getSign).distinct().collect(Collectors.toList());
            long existPermitSignCount = permitMapper
                    .selectCount(new LambdaQueryWrapper<Permit>().in(Permit::getSign, permitSignList));
            if(existPermitSignCount > 0){
                throw new BizServiceException("权限列表标识重复！");
            }
        }
        return Boolean.TRUE;
    }
}
